#include <iostream>
#include <string>
#include <functional>
#include <vector>
#include <time.h>
#include <unistd.h>
#include <pthread.h>

// typedef std::function<void()> func_t; 下面的写法和这句代码等价
using func_t = std::function<void()>;

#define threadnum 5

class ThreadData
{
public:
    ThreadData(const std::string &name, const uint64_t &ctime, func_t f)
        :threadname(name), createtime(ctime), func(f)
    {}

public:
    std::string threadname;
    uint64_t createtime;
    func_t func;
};

// void Print()
// {
//     std::cout << "我是线程执行的大任务的一部分" << std::endl;
// }

// 新线程
void *ThreadRountine(void *args)
{
    ThreadData *td = static_cast<ThreadData*>(args);
    while(true)
    {
        std::cout << "new thread." 
                  << " thread name: " << td->threadname 
                  << " create time: " << td->createtime 
                  << std::endl;
        sleep(1);
    }
}

int main()
{
    std::vector<pthread_t> pthreads;    // 存储线程的tid
    for (size_t i = 0; i < threadnum; i++)
    {
        char threadname[64];
        snprintf(threadname, sizeof(threadname), "%s-%lu", "thread", i);

        pthread_t tid;
        ThreadData *td = new ThreadData(threadname, (uint64_t)(time(nullptr)), nullptr);
        pthread_create(&tid, nullptr, ThreadRountine, td);
        pthreads.push_back(tid);
        sleep(1);       // 隔一秒创建一个线程
    }

    while(true)
    {
        // std::cout << "main thread" << std::endl;
        sleep(1);
    }
}